package com.ctgu.rabbitmq.config;

import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ ClassName RabbitMQConfig
 * @ Author Alex2
 * @ Date 2025/8/30 20:09
 **/
@Log4j2
@Configuration
public class RabbitMQConfig {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 开启 ReturnCallback 必须设置
        rabbitTemplate.setMandatory(true);

        // 消息没有路由到队列时触发
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            log.error("ReturnCallback-消息无法路由: exchange={}, routingKey={}, replyCode={}, replyText={}, message={}",
                    exchange, routingKey, replyCode, replyText, message);
        });

        // 消息是否到达交换机的确认回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            String id = null;
            if (correlationData != null) {
                id = correlationData.getId();
            }

            if (ack) {
                log.info("ConfirmCallback-消息成功到达交换机, id={}", id);
            } else {
                log.error("ConfirmCallback-消息未到达交换机, id={}, cause={}", id, cause);
            }
        });

        return rabbitTemplate;
    }
}